package com.chookss.home.audit.project;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.GroupEntity;
import com.chookss.home.entity.ReimbursementDetailEntity;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.OnlyOneEditText;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//项目金额  回款金额
public class GroupMoneyActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.edMoney)
    EditText edMoney;
    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.tvCurrentMoneyInit)
    TextView tvCurrentMoneyInit;
    @BindView(R.id.edMoneyInit)
    TextView edMoneyInit;
    @BindView(R.id.tvInit)
    TextView tvInit;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.tvCurrentMoney)
    TextView tvCurrentMoney;
    @BindView(R.id.common_right_iv)
    ImageView common_right_iv;
    @BindView(R.id.common_right_iv_ll)
    LinearLayout common_right_iv_ll;
    private int type = 0;//0项目金额 1回款金额
    private GroupEntity groupEntity;
    private String money="",repairCode="",workflowId="";
    private ReimbursementDetailEntity reimbursementDetailEntity=null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_money);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        edMoney.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        //限制输入的位数
        edMoney.addTextChangedListener(new OnlyOneEditText(edMoney).setInputNum(2));
        type = getIntent().getIntExtra("type", 0);
        repairCode=getIntent().getStringExtra("repairCode");
        groupEntity = (GroupEntity) getIntent().getSerializableExtra("groupEntity");
        tvCurrentMoneyInit.setText(ClearMoreZeroUtil.subZeroAndDot(money)+"元");
        if (type == 0) {
            commonTitleTxt.setText("项目金额");
            tvCurrentMoneyInit.setText("当前项目金额");
            edMoneyInit.setText("变更项目金额");
            tvInit.setText("修改项目金额，需通过审批后生效");
            if(Utils.isNull(repairCode)){
                tvCurrentMoney.setText(ClearMoreZeroUtil.subZeroAndDot(groupEntity.getSjAmtTotal()) + "元");
            }

        } else {
            commonTitleTxt.setText("回款金额");
            tvCurrentMoneyInit.setText("当前回款总金额");
            edMoneyInit.setText("本次回款金额");
            tvInit.setText("修改回款金额，需通过审批后生效");
            if(Utils.isNull(repairCode)) {
                tvCurrentMoney.setText(ClearMoreZeroUtil.subZeroAndDot(groupEntity.getReturnAmt()) + "元");
            }
            common_right_iv_ll.setVisibility(View.VISIBLE);
            LinearLayout.LayoutParams ivParams = (LinearLayout.LayoutParams) common_right_iv.getLayoutParams();
            ivParams.height = Utils.dip2px(this, 19);
            ivParams.width = Utils.dip2px(this, 17);
            common_right_iv.setLayoutParams(ivParams);
            common_right_iv.setBackgroundResource(R.drawable.kq_sh_icon);
        }
        if(!Utils.isNull(repairCode)) {
            selectDetail();
            tvSure.setText("修改");
        }
    }

    private void selectDetail() {
        //审批基本数据
        Map<String, String> map = new HashMap<>();
        map.put("projectCode", repairCode);
        if(type==0){
            map.put("type", "17");
        }else{
            map.put("type", "16");
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<ReimbursementDetailEntity>>() {
        }.getType(), null, Urls.selectKaoqinDeail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ReimbursementDetailEntity>() {
            @Override
            public void onSuccess(ReimbursementDetailEntity data) {
                dismissLoading();
                reimbursementDetailEntity=data;
                if (data != null) {
                    if (tvCurrentMoney == null) {
                        return;
                    }
                    workflowId=data.getWorkflowId();
                    tvCurrentMoney.setText(ClearMoreZeroUtil.subZeroAndDot(data.getOldAmt()) + "元");
                    edMoney.setText(ClearMoreZeroUtil.subZeroAndDot(data.getAmt()));
                    if (!Utils.isNull(data.getRemark())) {
                        edContent.setText(data.getRemark());
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void uploadData() {
        Map<String, Object> map = new HashMap<>();
        map.put("orgCode", new ShareUtils().getString(this, StaticClass.BELG_ORG_CODE, ""));
        map.put("orgName", new ShareUtils().getString(this, StaticClass.BELG_ORG_NAME, ""));
        if (!Utils.isNull(groupEntity.getGroupCode())) {
            map.put("groupCode", groupEntity.getGroupCode());
            map.put("groupName", groupEntity.getGroupName());
        }
        map.put("amt", edMoney.getText().toString());
        map.put("remark", edContent.getText().toString());
        if (type == 0) {
            map.put("amtType", "17");
            map.put("oldAmt", ClearMoreZeroUtil.subZeroAndDot(groupEntity.getSjAmtTotal()));
        } else {
            map.put("amtType", "16");
            map.put("oldAmt", ClearMoreZeroUtil.subZeroAndDot(groupEntity.getReturnAmt()));
        }
        showLoading();
        MyHttpRequest.postRequestJson(Urls.insertItemAmtInfo, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        EventBus.getDefault().post(new MyEvent("RefreshGroupRecord"));
                        MyToast.show("提交成功");
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }

            }
        });
    }
    private void updateData() {
        Map<String, Object> map = new HashMap<>();
        map.put("orgCode", new ShareUtils().getString(this, StaticClass.BELG_ORG_CODE, ""));
        map.put("orgName", new ShareUtils().getString(this, StaticClass.BELG_ORG_NAME, ""));
        if (!Utils.isNull(reimbursementDetailEntity.getGroupCode())) {
            map.put("groupCode", reimbursementDetailEntity.getGroupCode());
            map.put("groupName", reimbursementDetailEntity.getGroupName());
        }
        map.put("amt", edMoney.getText().toString());
        map.put("remark", edContent.getText().toString());
        map.put("workflowId", workflowId);
        map.put("itemAmtCode", repairCode);
        if (type == 0) {
            map.put("amtType", "17");
            map.put("oldAmt", ClearMoreZeroUtil.subZeroAndDot(reimbursementDetailEntity.getOldAmt()));
        } else {
            map.put("amtType", "16");
            map.put("oldAmt", ClearMoreZeroUtil.subZeroAndDot(reimbursementDetailEntity.getOldAmt()));
        }
        showLoading();
        MyHttpRequest.postRequestJson(Urls.updateItemAmtInfo, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        EventBus.getDefault().post(new MyEvent("RefreshSealRecord"));
                        MyToast.show("提交成功");
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }

            }
        });
    }

    @OnClick({R.id.common_title_back, R.id.common_right_iv_ll, R.id.tvSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_iv_ll:
                Intent intent = new Intent(this, ReturnMoneyRecordActivity.class);
                intent.putExtra("type", 16);
                intent.putExtra("groupCode", groupEntity.getGroupCode());
                startActivity(intent);
                break;
            case R.id.tvSure:
                if (Utils.isNull(edMoney.getText().toString())) {
                    MyToast.show("请输入金额");
                    return;
                }
                if (type == 1) {
                    if (Utils.isNull(edContent.getText().toString())) {
                        MyToast.show("请输入备注");
                        return;
                    }
                }
                if(!Utils.isNull(repairCode)){
                    updateData() ;
                }else{
                    uploadData();
                }
                break;
        }
    }

}
